<?php

namespace app\api\controller;
use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Request;
use think\Db;
/**
 * 购物车 123213
 */
class Cases extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 创建项目
     */

    public function addcases(){
        $data=$this->request->param();

        $uid=$this->auth->id;


        $user=Db::name('user')->where(['id'=>$uid])->find();

        /* 写地址记录 */
        $log=Db::name('address_log')->where(['uid'=>$uid,'address'=>$data['address']])->find();
        if (!$log){
            Db::name('address_log')->data(['uid'=>$uid,'address'=>$data['address']])->insert();
        }


        $merch=Db::name('aa_merch')->where(['id'=>$data['merch']])->find();

        $data['order']='STP1'.date('ymdH').rand(10,99);
        $data['uids']=trim($data['uids'],',');
        $data['types']=trim($data['types'],'_');
        $data['uid']=$uid;

        $data['title']=$data['titles'].'_'.$merch['title'].'_'.$data['types'];


        $data['time']=time();
        $data['startime']=$data['startime'].' '.$data['strtimeb'];
        $data['endtime']=$data['endtime'].' '.$data['endtimeb'];


        $data['timea']= strtotime($data['startime'].' '.$data['strtimeb']) ;
        $data['timeb']=strtotime($data['endtime'].' '.$data['endtimeb']);

        $data['xiangmu']=trim($data['xiangmu'],',');
        $data['new']=1;
        unset($data['strtimeb']);
        unset($data['endtimeb']);
        unset($data['titles']);


        $id=Db::name('aa_case')->insertGetId($data);

        $this->success('创建成功!',['id'=>$id]);

    }

    public function sendmessagebygzh(){

        $id=$this->request->param('id',0,'intval');

        $data=Db::name('aa_case')->where(['id'=>$id])->find();

        $user=Db::name('user')->where('id','eq',$data['uid'])->find();

        $userids=$data['uids'];
        $one=$user['nickname'];
        $icon=$data['title'];
        $times=date('y-m-d H:i');



        $users=Db::name('user')->where('id','in',$userids)->select();

        foreach ($users as $key){

            if  ($key['merch_id']==0){
                $this->ajaxurl($key['unionid'],$one,$icon,$times,$id);
            }else{
                $this->ajaxurlb($key['unionid'],$one,$icon,$times,$id);
            }
        }
    }

    public function ajaxurl($mobile,$one,$icons,$times,$id){
        $ch = curl_init();

        $url = "http://gzh.stp1.cn/api/message/sendmsgfroaddcase";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        $postData = array(
            'mobile' => $mobile,
            'one'=>$one,
            'sku' => $icons,
            'times' => $times,
            'id' => $id
        );

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        curl_close($ch);


    }


    public function ajaxurlb($mobile,$one,$icons,$times,$id){
        $ch = curl_init();

        $url = "http://gzh.stp1.cn/api/message/sendmsgfroaddcasetouser";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        $postData = array(
            'mobile' => $mobile,
            'one'=>$one,
            'sku' => $icons,
            'times' => $times,
            'id' => $id
        );

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);


    }


    /**
     * @return 项目详情
     */
    public function getcasebyid(){

        $id=$this->request->param('id');

      // ... existing code ...
        // 使用join方法关联cmf_aa_merch和cmf_user表
        $info = Db::name('aa_case')
            ->alias('c')
            ->join('cmf_aa_merch m', 'c.merch = m.id')
            ->join('cmf_user u', 'c.uid = u.id')
            ->where(['c.id' => $id])
            ->field('c.*,m.title as merch_title,m.logo,u.nickname,u.avatar')
            ->find();
// ... existing code ...


        $counts=Db::name('newphoto')->where(['caseid'=>$id])->count();


            Db::name('aa_case')->where(['id'=>$id])->update(['count'=>$counts]);





        $info['logo']=cdnurl($info['logo'],true);

        $users=Db::name('user')->where('id','in',$info['uids'])
            ->field('nickname,avatar,merch_id,name')->select();

        $info['users']=$users;


        $this->success('请求成功!', $info);


    }


    //获取上传用文件
    public function getcasesexcel(){

        $id=$this->request->param('id');

        $case=Db::name('aa_case')->alias('a')
            ->join('cmf_quotation b','a.q_id=b.id')
            ->where(['a.id'=>$id])
            ->field('a.*,b.order,b.id as quotation_id')->find();



        if($case&&$case['files']){
            $this->success('文件地址', $case['files']);
        }

        $list=Db::name('quotaion_log')->alias('a')
            ->join('cmf_catefrolist b','a.catefrolist_id=b.id')
            ->where(['a.quotation_id'=>$case['quotation_id'],'a.seesyatus'=>1])
            ->field('a.*,b.name')
            ->select();

        // 假设这里指定要修改的文件路径
        $fileToModify = "./upload/excel/demo.xlsx";

        // 加载已有的 Excel 文件
        $spreadsheet = IOFactory::load($fileToModify);
        $sheet = $spreadsheet->getActiveSheet();


        $headers = [];
        // 追加 $list 里的 name 值到 $headers 数组
        foreach ($list as $v) {
            $headers[] = '是/否';
        }

        $column = 'L';
        foreach ($headers as $header) {
            $sheet->setCellValue($column.'3', $header);
            $column++;
        }

        // 示例：修改表头
        $headers = [];
        // 追加 $list 里的 name 值到 $headers 数组
        foreach ($list as $v) {
            $headers[] = $v['name'];
        }

        $column = 'L';
        foreach ($headers as $header) {
            $sheet->setCellValue($column.'4', $header);
            $column++;
        }

        // 创建 Xlsx 写入器
        $writer = new Xlsx($spreadsheet);
        $savePath = "/upload/excel/";

        // 如果需要保存为新文件，可以指定新的文件名
        $newFileName = date('Y-m-d').$case['title'].'.xlsx';
        $newFullPath = '.'.$savePath . $newFileName;
        $writer->save($newFullPath);
        // ... existing code ...

        $file= cdnurl($savePath.$newFileName,true);
        Db::name('aa_case')->where(['id'=>$id])->update(['files'=>$file]);


        $this->success('文件地址', $file);

    }

    //项目参数

    public function getcasedata()
    {

        $id=$this->request->param('id');

        $v=Db::name('aa_case')->where(['id'=>$id])->find();

        $count1=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->count();


        $noin=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typein', 'eq', 0)
            ->count();


        $in=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typein', 'eq', 1)->count();

        $count3=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typeok', 'eq', 1)
            ->count();
        //未拍完
        $count4=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typesave', 'eq', 1)
            ->where('typetie', 'eq', 0)
            ->where('typecontroversy', 'eq', 0)
            ->count();
        //争议
        $count5=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typecontroversy','eq',1)
            ->count();

        $count6=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typetie', 'eq', 1)
            ->count();

        $count7=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typeout', 'eq', 1)
            ->count();

        $k['all'] =$count1;
        $k['noin'] =$noin;
        $k['in'] =$in;
        $k['save'] =$count3;
        $k['no'] =$count4;
        $k['zy'] =$count5;
        $k['dp'] =$count6;
        $k['ck'] =$count7;

        // 未出库
        $noout=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('typein', 'eq', 1)
            ->where('typeout', 'eq', 0)
            ->count();
        $k['noout'] =$noout;

        $man=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('sex', 'eq', '男')
            ->count();
        $k['man'] =$man;

        $woman=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('sex', 'neq', '男')
            ->count();
        $k['woman'] =$woman;


        $setcode=Db::name('newphoto')
            ->where('caseid', 'eq', $v['id'])
            ->where('setcode', 'eq', 1)
            ->count();
        $k['setcode'] =$setcode;



        $this->success('请求成功!', $k);

    }

    //列表信息
    public function getlistbytype(){
        $id=$this->request->param('id');
        $type=$this->request->param('type');

        $map['caseid']=['eq',$id];

        if ($type==1){
            $map['typein']=['eq',0];
        }elseif ($type==2){
            $map['typein']=['eq',1];
            $map['typeout']=['eq',0];
        }elseif ($type==3){
            $map['typein']=['eq',1];
            $map['typesave']=['eq',1];
        } elseif ($type==4){
            $map['typein']=['eq',1];
            $map['typeok']=['eq',1];
        }elseif ($type==5){
//            $map['typein']=['eq',1];
            $map['typetie']=['eq',1];
        }elseif ($type==6){
            $map['typein']=['eq',1];
            $map['typecontroversy']=['eq',1];
        }elseif ($type==7){
            $map['typein']=['eq',1];
            $map['typeout']=['eq',1];
        }elseif ($type==12){
            $map['setcode']=['eq',1];

        }elseif ($type==21){
            $map['sex']=['eq','男'];

        } elseif ($type==22){
            $map['sex']=['neq','男'];

        }



        $list=Db::name('newphoto')->where($map)->select();

        $case=Db::name('aa_case')->where(['id'=>$id])->find();


        foreach ($list as &$item){
            $t=$item['typeout']==1?' 退仓':' 未退';
            $item['title']= substr($case['title'],0,6)." ". $item['sku']." ".mb_substr($item['color1'],0,9).$t ;
        }

        $this->success('请求成功1!', $list);

    }


    /**
     * @return 修改状态
     */
    public function setordersuccess(){
        $id=$this->request->param('id');
        Db::name('aa_case')->where(['id'=>$id])->update(['status'=>1]);
        $this->success('操作成功!');
    }


    public function setcasestatus(){
        $id=$this->request->param('id');
        $type=$this->request->param('type');
        Db::name('aa_case_file')->where(['case_id'=>$id,'type'=>$type])
            ->update(['status'=>1]);

        $this->success('操作成功!');

    }


    //待办工资表
    public function getallfile(){

        $id=$this->request->param('id');

        $log=Db::name('aa_case_file')->where(['case_id'=>$id])->find();

        if (!$log){


            for ($a=1;$a<5;$a++){

                $data['case_id']=$id;
                $data['desc']='杨嘉伟于'.date('Y年 m月 d日').'更新';
                $data['type']=$a;

                if ($a==1){
                    $data['name']='创建报价单';
                }elseif ($a==2){
                    $data['name']='创建合同';
                }elseif ($a==3){
                    $data['name']='创建结算单';
                }elseif ($a==4){
                    $data['name']='创建发票';
                }

                Db::name('aa_case_file')->data($data)->insert();

            }

        }


        $logs=Db::name('aa_case_file')->where(['case_id'=>$id])->order('type asc')->select();

        $this->success('',$logs);

    }


    /**
        项目全部信息
     */
    public function getxumulistbyid(){

        $id=$this->request->param('id');

        $list=Db::name('newphoto')->where('caseid','eq',$id)->select();

        $this->success('项目',$list);

    }

    /**
     * 结算单  税率  税费
     * `taxrate` int(4) DEFAULT NULL COMMENT '税率',
     * `tax` decimal(10,2) DEFAULT NULL COMMENT '税费',
     * `createtime` bigint(20) DEFAULT NULL COMMENT '创建时间',
     * `updatetime` bigint(20) DEFAULT NULL COMMENT '修改时间',
     * `money`
     */
    public function getclearingbyid()
    {

        $id=$this->request->param('id');

        $info=Db::name('clearing')->where('caseid','eq',$id)->find();




        if($info){
            $lv=gettaxrate($info['taxrate']);
            //这里要计算下

            $money=Db::name('clearing_log')->where('caseid','eq',$id)->sum('allmoney');

            $tax=$money/100*$lv; //税

            $moneyb=$money+$tax; //税

            Db::name('clearing')->where('caseid','eq',$id)
                ->update(['moneyb'=>$moneyb,'tax'=>$tax,'money'=>$money,'createtime'=>time()]);

            $info=Db::name('clearing')->where('caseid','eq',$id)->find();


            $info['createtime0']=date('Y.m.d',$info['createtime']);
            $info['createtime1']=date('A H:i',$info['createtime']);

            $info['updatetime0']=date('Y.m.d',$info['updatetime']);
            $info['updatetime1']=date('A H:i',$info['updatetime']);

            $this->success('结算单',$info);
        }

        $case=Db::name('aa_case')
            ->alias('a')
            ->join('cmf_aa_merch b','a.merch=b.id')
            ->field('a.*,b.title as titlem')
            ->where('a.id','eq',$id)->find();


        $data['caseid']=$id;
        $data['name']=$case['title'];
        $data['order']='JS'.date('Hymd').$id;
        $data['merch']=$case['titlem'];
        $data['taxrate']=1;
        $data['tax']=0;
        $data['createtime']=time();
        $data['updatetime']=time();
        $data['money']=0;

        Db::name('clearing')->data($data)->insert();

        $data['createtime0']=date('Y.m.d',$data['createtime']);
        $data['createtime1']=date('A H:i',$data['createtime']);

        $data['updatetime0']=date('Y.m.d',$data['updatetime']);
        $data['updatetime1']=date('A H:i',$data['updatetime']);
        $this->success('结算单',$data);

    }

    /**
     * 结算单详情
     */
    public function getclearingdetail(){

        $id=$this->request->param('id');

        $case=Db::name('aa_case')->where('id','eq',$id)->find();


        $list=Db::name('clearing_log')->where('caseid','eq',$id)->order('id desc')->select();

        if  ($list){

            $this->success('结算单详情1',$list);
        }

        $lists=Db::name('quotaion_log')->alias('a')
            ->join('cmf_catefrolist b','a.catefrolist_id=b.id')
            ->where('a.quotation_id','eq',$case['q_id'])
            ->field('a.*,b.guige')
            ->select();

        foreach ($lists as $keys){

            $data['caseid']=$id;
            $data['catefrolist_id']=$keys['catefrolist_id'];
            $data['catefrolist_name']=$keys['catefrolist_name'];
            $data['size']=$keys['size'];
            $data['type']=$keys['type'];
            $data['money']=$keys['money'];
            $data['seesyatus']=$keys['seesyatus'];
            $data['desc']=$keys['desc'];
            $data['images']=$keys['images'];
            $data['icons']=$keys['icons'];
            $data['guige']=$keys['guige'];
            $sm=$keys['seesyatus']==0?$keys['money']:0;
            $num=$keys['seesyatus']==0?1:0;
            $data['allmoney']=$sm;
            $data['number']=$num;

            Db::name('clearing_log')->data($data)->insert();
        }

        $list=Db::name('clearing_log')->where('caseid','eq',$id)->select();


        $this->success('结算单详情2',$list);



    }

    /**
     *  修改清单的价格
     */
    public function setclearingmoneybyid(){
        $uid=$this->auth->id;
        $id=$this->request->param('id');
        $money=$this->request->param('money');

        Db::name('clearing_log')->where('id','eq',$id)->update(['allmoney'=>$money]);

        $info=Db::name('clearing_log')->where('id','eq',$id)->find();



        $log['clearing_id']=$info['caseid'];
        $log['user']=$uid;
        $log['desc']="修改清单的价格为：".$money;
        $log['time']=date('Y-m-d H:i:s');

        Db::name('clearing_setlog')->data($log)->insert();

        $this->success('修改成功');

    }


    /**
     * 制作详情
     */
    public function getmorelist(){

        $id = $this->request->param('id');

        $logs = Db::name('aa_case')
            ->alias('a')
            ->join('cmf_quotaion_log b', 'a.q_id=b.quotation_id')
            ->join('cmf_catefrolist c','b.catefrolist_id=c.id')
            ->where('a.id', $id)
            ->where('b.seesyatus','eq',1)
            ->field('b.*,c.images as goodimages')
            ->select();

        // 查询照片数据
        $photo = Db::name('newphoto')->where('caseid', $id)->select();

        // 将照片数据按 caseid 分组
        $photoGroup = [];
        foreach ($photo as $key) {
            $caseid = $key['caseid'];
            if (!isset($photoGroup[$caseid])) {
                $photoGroup[$caseid] = [];
            }
            $photoGroup[$caseid][] = $key;
        }

        $alls = [];

        // 处理逻辑
        foreach ($logs as $index => $keys) {
            $all = [];
            $arrays = [];
            $arraysb=[];

            if (isset($photoGroup[$id])) {
                foreach ($photoGroup[$id] as $key) {
                    try {
                        if (empty($key['more'])) {
                            throw new Exception("序列化数据为空");
                        }
                        $more = unserialize($key['more']);
                        if (!is_array($more) || !isset($more[$index]) || !isset($more[$index]['status']) || !isset($more[$index]['set'])) {
                            continue;
                        }
                        //拍摄
                        if ($more[$index]['status'] == 0 && $more[$index]['set'] == '是') {

                            $t=$key['typeout']==1?' 退仓':' 未退';


                            $array = [
                                'set' => $more[$index]['set'],
                                'code' => $key['code'],
                                'title' => $key['sku'] . "_" . $key['color1'].$t,
                                'status' => $more[$index]['status']
                            ];


                            $arrays[] = $array;
                        }

                        if ($more[$index]['status'] == 1 && $more[$index]['set'] == '是') {


                            $t=$key['typeout']==1?' 退仓':' 未退';
                            $array = [
                                'set' => $more[$index]['set'],
                                'code' => $key['code'],
                                'title' => $key['title'] . "_" . $key['color1'].$t,
                                'status' => $more[$index]['status']

                            ];


                            $arraysb[] = $array;
                        }
                    } catch (Exception $e) {
                        error_log("反序列化失败: " . $e->getMessage());
                    }
                }
            }

            $all['title'] = $keys['catefrolist_name'];
            $all['desc'] = $keys['desc'];

            $all['setimg'] = getallimages( $keys['images']);

            $all['icons'] = explode(',', $keys['icons']);
            $all['count'] = count($arrays);
            $all['list1'] = $arrays;
            $all['list2'] = $arraysb;
            $all['goodimages'] =getallimages1($keys['goodimages']);
            $alls[] = $all;
        }

        $this->success('制作信息',$alls);



    }


    /**
     * 修改税率 setsuilvbyid
     */

    public function setsuilvbyid(){


        $uid=$this->auth->id;
        $id=$this->request->param('id');
        $tax=$this->request->param('taxrate');

        Db::name('clearing')->where('caseid','eq',$id)->update(['taxrate'=>$tax]);

        //`clearing_id` int(11) DEFAULT NULL,
        //  `user` varchar(255) DEFAULT NULL COMMENT '修改人',
        //  `desc` varchar(255) DEFAULT NULL COMMENT '修改内容',
        //  `time` varchar(255) DEFAULT NULL COMMENT '修改时间',


        $log['clearing_id']=$id;
        $log['user']=$uid;
        $log['desc']='修改税率为'.$tax;
        $log['time']=date('Y-m-d H:i:s');

        Db::name('clearing_setlog')->data($log)->insert();




        $this->success('修改成功');

    }

    /**
     * 修改历史记录
     */
    public function getclearinglogbyid()
    {
        $id=$this->request->param('id');
        $list=Db::name('clearing_setlog')->alias('a')
            ->join('cmf_user b','a.user=b.id')
            ->field('a.*,b.nickname')
            ->where('a.clearing_id','eq',$id)
            ->order('a.id','desc')
            ->select();


        $this->success('修改历史记录',$list);
    }




}